//
//  BROrderListTableViewCell.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/28.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BROrderListTableViewCell.h"
#import "BRTools.h"

@implementation BROrderListTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.contentView.backgroundColor = UIColor.clearColor;
    self.backgroundColor = UIColor.clearColor;
    self.bgView.backgroundColor = UIColor.whiteColor;
    self.statusLB.textColor = kColorTitle;
    self.statusLB.font = [UIFont fontS:17];
    self.priceLB.textColor = kColorTitle;
    self.priceLB.font = [UIFont fontB:20];
    self.estimatedLB.textColor = UIColor.qd_titleTextColor;
    self.estimatedLB.font = [UIFont fontM:12];
    // timeLB 和 branchLB 已移除，信息现在通过 infoContainerView 显示
    self.statueView.layer.cornerRadius = 3;
    self.statueView.layer.masksToBounds = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toPayOrBuy)];
    [self.bottomView addGestureRecognizer:tap];
    
    self.bottomL.textColor = kColorMain;
    self.bottomL.font = [UIFont fontS:14];
    
    self.line.backgroundColor = UIColorMakeWithHex(@"#D2D8E2");
    
//    self.bottomArrowImg.image = UIImageMake(@"");
    
    self.estimatedLB.text = Localized(@"Order_estimated");
    self.estimatedLB.hidden = YES;
    
    NSString *btText =  Localized(@"home_gotoPay");
    self.bottomL.text = btText;
    
    // 创建并添加信息 label
    [self setupInfoLabels];
}

// 去支付或者取购买
- (void)toPayOrBuy {
    
//    NSInteger index = self.dto.state == 1 ? 0 : 1;
    if (self.toPayBlock) {
        self.toPayBlock(self.dto.state);
    }
    
}


- (void)setDto:(BROrderListModel *)dto {
    _dto = dto;
    
    // 优先使用新接口的 usingStatus，如果没有则使用 state
    NSInteger status = dto.usingStatus > 0 ? dto.usingStatus : dto.state;
    self.status = status;
    
    // 判断是否显示底部按钮（待支付状态）
    BOOL hasBottom = dto.state == 2;
//    if (self.type == 1) hasBottom = NO;
    self.hasBottom = hasBottom;
   
    // branchLB 和 timeLB 已移除，时间等信息现在通过 updateInfoLabels 在 infoContainerView 中显示
    
    NSDecimalNumber *amount = dto.realAmount;
    if (dto.state == 2) {
        amount = dto.money;
    }
    if (dto.state == 5) {
        amount = dto.orderAmount;
    }
    
    // 使用全局金额格式化函数（处理百分位），参考订单详情页
    NSDecimalNumber *displayAmount = amount ? amount : [NSDecimalNumber decimalNumberWithString:@"0"];
    NSString *amountStr = [BRTools br_formatVietnameseDong:displayAmount.doubleValue];
    self.priceLB.text = [NSString stringWithFormat:@"%@₫", amountStr];
    
    // 更新信息 label
    [self updateInfoLabels];
    [self setNeedsLayout]; // 触发布局更新
    [self layoutIfNeeded]; // 立即执行布局，确保 label 显示
}

- (void)setupInfoLabels {
    if (self.infoContainerView) {
        return; // 已创建
    }
    
    // 创建容器视图
    self.infoContainerView = [[UIView alloc] init];
    self.infoContainerView.backgroundColor = UIColor.clearColor;
    self.infoContainerView.translatesAutoresizingMaskIntoConstraints = NO;
    self.infoContainerView.hidden = NO; // 确保可见
    [self.bgView addSubview:self.infoContainerView];
    
    // 创建各个 label
    self.orderNoLB = [self createInfoLabel];
    self.cabinetSNLB = [self createInfoLabel];
    self.rentTimeLB = [self createInfoLabel];
    self.rentLocationLB = [self createInfoLabel];
    self.billingRuleLB = [self createInfoLabel];
    self.billingRuleLB.numberOfLines = 0; // 允许多行显示
    
    [self.infoContainerView addSubview:self.orderNoLB];
    [self.infoContainerView addSubview:self.cabinetSNLB];
    [self.infoContainerView addSubview:self.rentTimeLB];
    [self.infoContainerView addSubview:self.rentLocationLB];
    [self.infoContainerView addSubview:self.billingRuleLB];
    
    // 设置容器视图的约束
    UIView *topContainer = self.statusLB.superview;
    NSLayoutConstraint *leadingConstraint = [NSLayoutConstraint constraintWithItem:self.infoContainerView
                                                                          attribute:NSLayoutAttributeLeading
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:self.bgView
                                                                          attribute:NSLayoutAttributeLeading
                                                                         multiplier:1.0
                                                                           constant:14];
    NSLayoutConstraint *trailingConstraint = [NSLayoutConstraint constraintWithItem:self.infoContainerView
                                                                           attribute:NSLayoutAttributeTrailing
                                                                           relatedBy:NSLayoutRelationEqual
                                                                              toItem:self.bgView
                                                                           attribute:NSLayoutAttributeTrailing
                                                                          multiplier:1.0
                                                                            constant:-14];
    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:self.infoContainerView
                                                                       attribute:NSLayoutAttributeTop
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:topContainer
                                                                       attribute:NSLayoutAttributeBottom
                                                                      multiplier:1.0
                                                                        constant:12];
    
    [self.bgView addConstraint:leadingConstraint];
    [self.bgView addConstraint:trailingConstraint];
    [self.bgView addConstraint:topConstraint];
    
    // 更新底部按钮的约束，使其位于信息容器下方
    // 先移除可能存在的旧约束
    NSMutableArray *constraintsToRemove = [NSMutableArray array];
    for (NSLayoutConstraint *constraint in self.bgView.constraints) {
        if (constraint.firstItem == self.bottomView && constraint.firstAttribute == NSLayoutAttributeTop) {
            if (constraint.secondItem == topContainer || constraint.secondItem == self.infoContainerView) {
                [constraintsToRemove addObject:constraint];
            }
        }
    }
    for (NSLayoutConstraint *constraint in constraintsToRemove) {
        constraint.active = NO;
    }
    
    // 添加新约束：底部按钮顶部应该 >= 信息容器底部
    NSLayoutConstraint *bottomTopConstraint = [NSLayoutConstraint constraintWithItem:self.bottomView
                                                                           attribute:NSLayoutAttributeTop
                                                                           relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                                              toItem:self.infoContainerView
                                                                           attribute:NSLayoutAttributeBottom
                                                                          multiplier:1.0
                                                                            constant:0];
    bottomTopConstraint.priority = 750; // 低于必需优先级，允许在有足够空间时生效
    [self.bgView addConstraint:bottomTopConstraint];
    
    // 同时保留一个指向顶部容器的低优先级约束作为 fallback（如果 infoContainerView 不存在）
    NSLayoutConstraint *fallbackConstraint = [NSLayoutConstraint constraintWithItem:self.bottomView
                                                                          attribute:NSLayoutAttributeTop
                                                                          relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                                             toItem:topContainer
                                                                          attribute:NSLayoutAttributeBottom
                                                                         multiplier:1.0
                                                                           constant:0];
    fallbackConstraint.priority = 250;
    [self.bgView addConstraint:fallbackConstraint];
    
    // 布局
    [self layoutInfoLabels];
}

- (UILabel *)createInfoLabel {
    UILabel *label = [[UILabel alloc] init];
    label.textColor = kColorTitle66B;
    label.font = [UIFont fontM:13];
    label.numberOfLines = 1;
    label.backgroundColor = UIColor.clearColor; // 确保背景透明
    label.hidden = NO; // 确保可见
    return label;
}

- (void)layoutInfoLabels {
    // 延迟布局，在layoutSubviews中更新frame
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (self.infoContainerView && self.bgView) {
        CGFloat spacing = 6;
        CGFloat labelHeight = 18;
        // 使用 bgView 的宽度来计算容器宽度，而不是 infoContainerView 的宽度（可能还未计算）
        CGFloat containerWidth = self.bgView.frame.size.width - 28; // 左右各14的边距
        
        // 如果容器宽度为0，等待下次布局
        if (containerWidth <= 0) {
            return;
        }
        
        CGFloat currentY = 0;
        
        // 确保所有 label 都可见
        self.orderNoLB.hidden = NO;
        self.cabinetSNLB.hidden = NO;
        self.rentTimeLB.hidden = NO;
        self.rentLocationLB.hidden = NO;
        self.billingRuleLB.hidden = NO;
        
        // 订单编号
        self.orderNoLB.frame = CGRectMake(0, currentY, containerWidth, labelHeight);
        currentY += labelHeight + spacing;
        
        // 柜机SN
        self.cabinetSNLB.frame = CGRectMake(0, currentY, containerWidth, labelHeight);
        currentY += labelHeight + spacing;
        
        // 租借时间
        self.rentTimeLB.frame = CGRectMake(0, currentY, containerWidth, labelHeight);
        currentY += labelHeight + spacing;
        
        // 租借地点
        self.rentLocationLB.frame = CGRectMake(0, currentY, containerWidth, labelHeight);
        currentY += labelHeight + spacing;
        
        // 计费规则（多行）
        CGFloat ruleHeight = [self.billingRuleLB.text boundingRectWithSize:CGSizeMake(containerWidth, CGFLOAT_MAX)
                                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                                 attributes:@{NSFontAttributeName: self.billingRuleLB.font}
                                                                    context:nil].size.height;
        ruleHeight = MAX(ruleHeight, labelHeight);
        self.billingRuleLB.frame = CGRectMake(0, currentY, containerWidth, ruleHeight);
        currentY += ruleHeight;
        
        // 更新容器视图高度约束
        for (NSLayoutConstraint *constraint in self.infoContainerView.constraints) {
            if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                constraint.constant = currentY;
                break;
            }
        }
        
        // 如果没有找到高度约束，创建一个
        BOOL hasHeightConstraint = NO;
        for (NSLayoutConstraint *constraint in self.infoContainerView.constraints) {
            if (constraint.firstAttribute == NSLayoutAttributeHeight && constraint.firstItem == self.infoContainerView) {
                hasHeightConstraint = YES;
                break;
            }
        }
        if (!hasHeightConstraint) {
            NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.infoContainerView
                                                                                attribute:NSLayoutAttributeHeight
                                                                                relatedBy:NSLayoutRelationEqual
                                                                                   toItem:nil
                                                                                attribute:NSLayoutAttributeNotAnAttribute
                                                                               multiplier:1.0
                                                                                 constant:currentY];
            [self.infoContainerView addConstraint:heightConstraint];
        }
        
        // 确保容器视图可见
        self.infoContainerView.hidden = NO;
    }
}

- (void)updateInfoLabels {
    BROrderListModel *dto = self.dto;
    
    // 订单编号 - 显示 uuid
    NSString *orderNoStr = dto.uuid.length > 0 ? dto.uuid : (dto.orderNo.length > 0 ? dto.orderNo : @"--");
    self.orderNoLB.text = [NSString stringWithFormat:@"%@%@", Localized(@"order_orderNumberColon"), orderNoStr];
    
    // 柜机SN - 使用 box1DeviceId，如果没有则使用 box1DeviceUuid
    NSString *cabinetSN = dto.box1DeviceId.length > 0 ? dto.box1DeviceId : (dto.box1DeviceUuid.length > 0 ? dto.box1DeviceUuid : @"");
    if (cabinetSN.length == 0 && dto.singleDeviceUuid.length > 0) {
        cabinetSN = dto.singleDeviceUuid;
    }
    if (cabinetSN.length == 0 && dto.rentCabinetNo.length > 0) {
        cabinetSN = dto.rentCabinetNo;
    }
    self.cabinetSNLB.text = [NSString stringWithFormat:@"%@%@", Localized(@"order_cabinetSNColon"), cabinetSN.length > 0 ? cabinetSN : @"--"];
    
    // 租借时间 - 优先使用 borrowTime（时间戳），然后是 createTime
    NSString *rentTimeStr = @"--";
    if (dto.borrowTime > 0) {
        rentTimeStr = [BRTools getTimeFromTimestamp:dto.borrowTime formatter:@"yyyy-MM-dd HH:mm:ss"];
    } else if (dto.createTime.length > 0) {
        rentTimeStr = [BRTools getTimeFromTimestamp:dto.createTime.integerValue formatter:@"yyyy-MM-dd HH:mm:ss"];
    }
    self.rentTimeLB.text = [NSString stringWithFormat:@"%@%@", Localized(@"order_rentTimeColon"), rentTimeStr];
    
    // 租借地点 - 优先使用 box1SiteName，然后是 rentBranchName
    NSString *location = dto.box1SiteName.length > 0 ? dto.box1SiteName : (dto.rentBranchName.length > 0 ? dto.rentBranchName : Localized(@"order_unknownLocation"));
    self.rentLocationLB.text = [NSString stringWithFormat:@"%@%@", Localized(@"order_rentLocationColon"), location];
    
    // 计费规则 - 按照 Android 逻辑
    NSString *ruleStr = @"--";
    if (dto.ruleMinuteFree > 0 || dto.ruleMinuteCycle > 0 || (dto.ruleDayFee && dto.ruleDayFee.doubleValue > 0) || (dto.ruleSecurityFee && dto.ruleSecurityFee.doubleValue > 0)) {
        NSMutableString *rule = [NSMutableString string];
        
        // 免费分钟数
        if (dto.ruleMinuteFree > 0) {
            [rule appendFormat:Localized(@"rule_firstMinutesFree"), (int)dto.ruleMinuteFree];
        }
        
        // 每周期费用 - 使用全局金额格式化函数（处理百分位）
        if (dto.ruleMinuteCycle > 0 && dto.ruleCycleFee) {
            if (rule.length > 0) {
                [rule appendString:@","];
            }
            NSString *formattedCycleFee = [BRTools br_formatVietnameseDong:dto.ruleCycleFee.doubleValue];
            [rule appendFormat:Localized(@"rule_cycleFeeFormat"), formattedCycleFee, (int)dto.ruleMinuteCycle];
        }
        
        // 每日封顶费用 - 使用全局金额格式化函数（处理百分位）
        if (dto.ruleDayFee && dto.ruleDayFee.doubleValue > 0) {
            if (rule.length > 0) {
                [rule appendString:@","];
            }
            NSString *formattedDayFee = [BRTools br_formatVietnameseDong:dto.ruleDayFee.doubleValue];
            [rule appendFormat:Localized(@"rule_dayFeeFormat"), formattedDayFee];
        }
        
        // 押金费用 - 使用全局金额格式化函数（处理百分位）
        if (dto.ruleSecurityFee && dto.ruleSecurityFee.doubleValue > 0) {
            if (rule.length > 0) {
                [rule appendString:@","];
            }
            NSString *formattedSecurityFee = [BRTools br_formatVietnameseDong:dto.ruleSecurityFee.doubleValue];
            [rule appendFormat:Localized(@"rule_securityFeeFormat"), formattedSecurityFee];
        }
        
        ruleStr = rule.length > 0 ? rule : @"--";
    } else if (dto.billing) {
        // 使用旧接口的 billing 对象
        ruleStr = [USERManager br_ruleOfModel:dto.billing];
    }
    self.billingRuleLB.text = [NSString stringWithFormat:@"%@%@", Localized(@"order_billingRuleColon"), ruleStr];
    [self setNeedsLayout]; // 更新计费规则后重新布局
}

- (void)setHasBottom:(BOOL)hasBottom {
    _hasBottom = hasBottom;
    
    self.bottomView.hidden = !hasBottom;
    self.bottomH.constant = hasBottom ? 44 : 0;
}

- (void)setStatus:(NSInteger)status {
    _status = status;
    
    // 判断是否使用新接口的 usingStatus（1-6）
    if (self.dto.usingStatus > 0) {
        // 使用新接口的状态和颜色
        self.statueView.backgroundColor = [BRTools colorOrderUsingStatus:status];
        self.statusLB.text = [BRTools strOrderUsingStatus:status];
    } else {
        // 使用旧接口的 state
        self.statueView.backgroundColor = [self getStatusInOrder:status];
        self.statusLB.text = [BRTools strOrderOfType:status];
    }
}

- (UIColor *)getStatusInOrder:(NSInteger)status {
    self.estimatedLB.text = Localized(@"Order_actualPayment");
    

    //如果是部分退款或全部退款
    if (self.dto.paymentState == 3) {
        self.estimatedLB.text = Localized(@"Payment_partialRefunded");//"Payment_partialRefunded" = "Partial refunded";
    }
    if (self.dto.paymentState == 4) {
        self.estimatedLB.text = Localized(@"Payment_fullyRefunded");
    }
    
    // 如果是新接口的 usingStatus，使用新接口的颜色方法
    if (self.dto.usingStatus > 0) {
        return [BRTools colorOrderUsingStatus:self.dto.usingStatus];
    }
    
    // 旧接口的 state 逻辑
    if (status == 7) {
        return UIColorMakeWithHex(@"#FF605A");
    }
    
    if (status == 2 || status == 5) {
        return UIColorMakeWithHex(@"#FFC855");
    }
    if (status == 1) {
//        self.estimatedLB.text = Localized(@"Order_estimated");
        return UIColorMakeWithHex(@"#1295FF");
    }
    
    return UIColorMakeWithHex(@"#4CE48A");
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
